import tkinter as tk
from tkinter import ttk, messagebox
import sqlite3
import re
from werkzeug.security import generate_password_hash, check_password_hash
import pickle
import os


# ===================== 数据库管理模块 =====================
class DatabaseManager:
    def __init__(self):
        self.conn = sqlite3.connect('users.db')
        self.create_table()

    def create_table(self):
        cursor = self.conn.cursor()
        cursor.execute('''CREATE TABLE IF NOT EXISTS users (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        username TEXT UNIQUE NOT NULL,
                        password TEXT NOT NULL,
                        phone TEXT UNIQUE NOT NULL)''')
        self.conn.commit()

    def register_user(self, username, password, phone):
        try:
            cursor = self.conn.cursor()
            cursor.execute("INSERT INTO users (username, password, phone) VALUES (?, ?, ?)",
                           (username, generate_password_hash(password), phone))
            self.conn.commit()
            return True
        except sqlite3.IntegrityError:
            return False

    def verify_user(self, username, password):
        cursor = self.conn.cursor()
        cursor.execute("SELECT password FROM users WHERE username=?", (username,))
        result = cursor.fetchone()
        return result and check_password_hash(result[0], password)


# ===================== 职业测评模块 =====================
class CareerAssessment:
    def __init__(self, parent, username):
        self.parent = parent
        self.username = username
        self.answers = {}
        self.setup_ui()

    def setup_ui(self):
        self.assessment_window = tk.Toplevel(self.parent)
        self.assessment_window.title("职业能力测评")
        self.assessment_window.geometry("600x500")

        # 问题配置
        self.questions = [
            {
                "text": "1. 您当前的职业阶段？",
                "options": ["在校学生", "应届毕业生", "1-3年工作经验", "3年以上工作经验"]
            },
            {
                "text": "2. 您满意当前的职业吗？",
                "options": ["非常满意", "比较满意", "一般", "不满意"]
            },
            {
                "text": "3. 最希望提升的技能方向？",
                "options": ["技术能力", "管理能力", "沟通能力", "行业专业知识"]
            },
            {
                "text": "4. 期望的行业领域？",
                "options": ["信息技术", "金融投资", "教育培训", "医疗健康", "智能制造"]
            }
        ]

        # 主容器
        main_frame = tk.Frame(self.assessment_window, padx=20, pady=20)
        main_frame.pack(fill=tk.BOTH, expand=True)

        # 标题
        tk.Label(main_frame,
                 text="职业能力测评问卷",
                 font=("黑体", 16),
                 fg="#2A5CAA").pack(pady=10)

        # 问题区
        self.answer_vars = []
        for idx, question in enumerate(self.questions):
            frame = tk.Frame(main_frame)
            frame.pack(pady=8, fill=tk.X)

            tk.Label(frame,
                     text=question["text"],
                     font=("宋体", 12),
                     anchor="w").pack(side=tk.LEFT)

            var = tk.StringVar()
            self.answer_vars.append(var)
            option_menu = ttk.Combobox(
                frame,
                textvariable=var,
                values=question["options"],
                state="readonly",
                width=20
            )
            option_menu.pack(side=tk.RIGHT, padx=10)
            option_menu.current(0)

        # 提交按钮
        tk.Button(main_frame,
                  text="生成测评报告",
                  command=self.generate_report,
                  bg="#2A5CAA",
                  fg="white",
                  padx=20,
                  pady=5).pack(pady=20)

    def generate_report(self):
        # 收集答案
        self.answers = {
            "stage": self.answer_vars[0].get(),
            "satisfaction": self.answer_vars[1].get(),
            "skill": self.answer_vars[2].get(),
            "industry": self.answer_vars[3].get()
        }

        # 生成报告内容
        report_content = f"""
        【{self.username}的职业测评报告】

        当前职业阶段：{self.answers['stage']}
        职业满意度：{self.answers['satisfaction']}
        技能提升方向：{self.answers['skill']}
        期望行业领域：{self.answers['industry']}

        【发展建议】
        1. 根据您的职业阶段，推荐参加{"校园招聘" if "学生" in self.answers['stage'] else "行业峰会"}
        2. 针对{self.answers['skill']}提升，建议学习相关在线课程
        3. {self.answers['industry']}领域近期有大量岗位需求
        """

        # 显示报告窗口
        report_window = tk.Toplevel(self.assessment_window)
        report_window.title("测评报告")
        report_window.geometry("500x400")

        # 保存报告
        tk.Button(report_window,
                  text="保存报告",
                  command=lambda: self.save_report(report_content),
                  bg="#4CAF50",
                  fg="white").pack(pady=10)

    def save_report(self, content):
        filename = f"{self.username}_职业测评报告.txt"
        with open(filename, "w", encoding="utf-8") as f:
            f.write(content)
        messagebox.showinfo("保存成功", f"报告已保存为：{filename}")

    # ===================== 主应用界面模块 =====================
    class MainApplication:
        def __init__(self, master, username):
            self.master = master
            self.username = username
            self.setup_ui()

        def setup_ui(self):
            self.master.title("职智蔚来 - AI职路导航")
            self.master.geometry("800x600")

            # 主题色配置
            self.primary_color = "#2A5CAA"
            self.secondary_color = "#FFFFFF"
            self.highlight_color = "#6C9BD2"

            # 主容器
            self.main_frame = tk.Frame(self.master, bg=self.primary_color)
            self.main_frame.pack(fill=tk.BOTH, expand=True)

            # 标题栏
            self.header = tk.Frame(self.main_frame, bg=self.primary_color)
            self.header.pack(pady=20)

            self.logo_label = tk.Label(
                self.header,
                text="职智蔚来",
                font=("微软雅黑", 24, "bold"),
                fg=self.secondary_color,
                bg=self.primary_color
            )
            self.logo_label.pack()

            self.subtitle_label = tk.Label(
                self.header,
                text=f"欢迎您，{self.username}！AI职路导航 · 为社会服务",
                font=("微软雅黑", 12),
                fg=self.highlight_color,
                bg=self.primary_color
            )
            self.subtitle_label.pack(pady=10)
            # 新增版权信息（在状态栏下方）
            tk.Label(
                self.master,
                text="© 2024 职智蔚来 版权所有",
                font=("宋体", 10),
                fg="#696969",
                bg="#F0F8FF"
            ).pack(side=tk.BOTTOM, pady=10)  # 保持在最底部

            # 功能导航区
            self.nav_frame = tk.Frame(self.main_frame, bg=self.secondary_color)
            self.nav_frame.pack(pady=30, padx=50, fill=tk.X)

            # 导航按钮
            nav_buttons = [
                ("智能职业测评", self.show_assessment),
                ("技能提升计划", self.show_skills),
                ("精准岗位匹配", self.show_jobs),
                ("职场导师社区", self.show_community)
            ]

            for text, command in nav_buttons:
                btn = tk.Button(
                    self.nav_frame,
                    text=text,
                    font=("宋体", 14),
                    bg=self.highlight_color,
                    fg=self.secondary_color,
                    relief=tk.FLAT,
                    command=command
                )
                btn.pack(side=tk.LEFT, expand=True, padx=10, ipady=10)

            # 内容展示区
            self.content_frame = tk.Frame(self.main_frame, bg=self.secondary_color)
            self.content_frame.pack(fill=tk.BOTH, expand=True, padx=50, pady=20)

            # 初始化默认内容
            self.show_welcome()

            # 状态栏
            self.status_bar = tk.Label(
                self.master,
                text="v1.0 | 让AI助力每个人的职业发展",
                bd=1,
                relief=tk.SUNKEN,
                anchor=tk.W,
                font=("宋体", 10)
            )
            self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

        def show_welcome(self):
            self.clear_content()
            welcome_text = f"""
                {self.username}，欢迎使用职智蔚来AI导航系统！

                我们为您提供：
                ✅ 智能职业能力测评
                ✅ 个性化技能提升方案
                ✅ 精准岗位匹配推荐
                ✅ 职场导师在线社区
                """
            label = tk.Label(
                self.content_frame,
                text=welcome_text,
                font=("宋体", 14),
                justify=tk.LEFT,
                bg=self.secondary_color
            )
            label.pack(pady=50)

        def show_assessment(self):
            CareerAssessment(self.master, self.username)

        def clear_content(self):
            for widget in self.content_frame.winfo_children():
                widget.destroy()

        def show_skills(self):
            self.clear_content()
            messagebox.showinfo("开发中", "技能提升模块即将上线！")

        def show_jobs(self):
            self.clear_content()
            messagebox.showinfo("开发中", "岗位匹配模块即将上线！")

        def show_community(self):
            self.clear_content()
            messagebox.showinfo("开发中", "社区交流模块即将上线！")

    # ===================== 认证系统模块 =====================
    class AuthSystem:
        def __init__(self, root):
            self.root = root
            self.db = DatabaseManager()
            self.load_remembered_user()
            self.setup_ui()

        def load_remembered_user(self):
            self.remembered_user = None
            if os.path.exists('remember.me'):
                with open('remember.me', 'rb') as f:
                    self.remembered_user = pickle.load(f)

        def setup_ui(self):
            self.root.title("职智蔚来 - 用户认证系统")
            self.root.geometry("500x400")

            # 主题配置
            self.style = ttk.Style()
            self.style.configure('TLabel', font=('微软雅黑', 12))
            self.style.configure('TButton', font=('宋体', 12))

            self.notebook = ttk.Notebook(self.root)
            self.login_tab = ttk.Frame(self.notebook)
            self.register_tab = ttk.Frame(self.notebook)

            self.notebook.add(self.login_tab, text="登录")
            self.notebook.add(self.register_tab, text="注册")
            self.notebook.pack(expand=True, fill='both', padx=20, pady=20)

            self.create_login_tab()
            self.create_register_tab()

        def create_login_tab(self):
            # 登录表单
            ttk.Label(self.login_tab, text="用户名:").grid(row=0, column=0, padx=10, pady=10, sticky='e')
            self.login_user = ttk.Entry(self.login_tab)
            self.login_user.grid(row=0, column=1, padx=10, pady=10)

            ttk.Label(self.login_tab, text="密码:").grid(row=1, column=0, padx=10, pady=10, sticky='e')
            self.login_pass = ttk.Entry(self.login_tab, show="*")
            self.login_pass.grid(row=1, column=1, padx=10, pady=10)

            self.remember_me = tk.BooleanVar()
            ttk.Checkbutton(self.login_tab, text="记住我", variable=self.remember_me).grid(row=2, column=1, sticky='w')

            ttk.Button(self.login_tab, text="登录", command=self.handle_login).grid(row=3, column=1, pady=20,
                                                                                    sticky='e')

            # 自动填充记住的用户
            if self.remembered_user:
                self.login_user.insert(0, self.remembered_user)
                self.login_pass.focus()

        def create_register_tab(self):
            # 注册表单
            ttk.Label(self.register_tab, text="用户名:").grid(row=0, column=0, padx=10, pady=10, sticky='e')
            self.reg_user = ttk.Entry(self.register_tab)
            self.reg_user.grid(row=0, column=1, padx=10, pady=10)

            ttk.Label(self.register_tab, text="密码:").grid(row=1, column=0, padx=10, pady=10, sticky='e')
            self.reg_pass = ttk.Entry(self.register_tab, show="*")
            self.reg_pass.grid(row=1, column=1, padx=10, pady=10)

            ttk.Label(self.register_tab, text="联系电话:").grid(row=2, column=0, padx=10, pady=10, sticky='e')
            self.reg_phone = ttk.Entry(self.register_tab)
            self.reg_phone.grid(row=2, column=1, padx=10, pady=10)

            ttk.Button(self.register_tab, text="立即注册", command=self.handle_register).grid(row=3, column=1, pady=20,
                                                                                              sticky='e')

        def validate_phone(self, phone):
            return re.match(r'^1[3-9]\d{9}$', phone)

        def handle_login(self):
            username = self.login_user.get()
            password = self.login_pass.get()

            if not all([username, password]):
                messagebox.showerror("错误", "请填写完整登录信息")
                return

            if self.db.verify_user(username, password):
                if self.remember_me.get():
                    with open('remember.me', 'wb') as f:
                        pickle.dump(username, f)
                self.show_main_interface(username)
            else:
                messagebox.showerror("错误", "用户名或密码错误")

        def handle_register(self):
            username = self.reg_user.get()
            password = self.reg_pass.get()
            phone = self.reg_phone.get()

            if not all([username, password, phone]):
                messagebox.showerror("错误", "请填写所有注册信息")
                return

            if not self.validate_phone(phone):
                messagebox.showerror("错误", "请输入有效的11位手机号码")
                return

            if self.db.register_user(username, password, phone):
                messagebox.showinfo("成功", "注册成功，请登录")
                self.notebook.select(0)
            else:
                messagebox.showerror("错误", "用户名或手机号已被注册")

        def show_main_interface(self, username):
            self.root.destroy()
            main_win = tk.Tk()
            MainApplication(main_win, username)
            main_win.mainloop()

    # ===================== 主程序入口 =====================
    if __name__ == "__main__":
        root = tk.Tk()
        app = AuthSystem(root)
        root.mainloop()
        text_area = tk.Text(report_window, wrap=tk.WORD, font=("宋体", 12))
        text_area.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        text_area.insert(tk.END, report_content)
        text_area.config(state=tk.DISABLED)




    